package jdbc;/*
 *
 * @author 陈粒
 * @version 创建时间：2021/7/31 10:14
 */

import java.sql.*;
import java.util.Scanner;

/**
 * 采用占位符解决sql注入问题
 */
public class JDBC_New_Login {
    public static void main(String[] args) {
        System.out.println("请输入名字：");
        String s1 = new Scanner(System.in).nextLine();
        System.out.println("请输入密码：");
        String s2 = new Scanner(System.in).nextLine();
        Connection conn = null;
        PreparedStatement pstm = null;//采用PreparedStatement传输器，比Statement传输器优点多，可以使用占位符
        ResultSet resultSet = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teacher", "root", "root");
            String sql = "select * from login where name = ? and password = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, s1);//设置占位符位置
            pstm.setString(2, s2);//设置占位符位置
            resultSet = pstm.executeQuery();
            if (resultSet.next()) {
                System.out.println("恭喜你,登录成功");
            } else {
                System.out.println("输入错误，请重新输入");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (pstm != null) {
                try {
                    pstm.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
